﻿using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    public class ArticleController : Controller
    {
        DBContext db;

        public ArticleController()
            : this(null)
        { 
            
        }
        
        public ArticleController(DBContext mockDB)
        {
            if (mockDB == null)
            {
                db = new DBContext();
            }
            else {
                db = mockDB;
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //如果传入条件参数
            name = HttpUtility.UrlDecode(name);
            List<ArticleModel> list = new List<ArticleModel>();
            int totalCount = 0;
            string where = string.Format(" title like '%{0}%'", name);
            if (!string.IsNullOrEmpty(name))
            {
                list = db.Articles.GetList(pageSize, currentPage,where );
                totalCount = db.Articles.GetRecordCount(where);
            }
            else
            {
                list = db.Articles.GetList(pageSize, currentPage, "");
                totalCount = db.Articles.GetRecordCount("");
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        public ActionResult Show(int ID)
        {
            ArticleModel model = db.Articles.GetModel(ID);
            InitTemplateType(model.TemplateID);
            InitCategoryType(model.CategoryCode);
            return View(model);
        }

        public JsonResult Single(int id)
        {
            ArticleModel model = db.Articles.GetModel(id);
            return Json(new { code = SaveStateEnum.OK.ToString(), data = model });
        }

        public ActionResult Create()
        {           
            //根据当前栏目，计算新栏目的code值
            ArticleModel model = new ArticleModel();
            InitTemplateType(0);
            InitCategoryType("00");
            return View(model);
        }

        //栏目，查询首页模板和栏目模板，栏目一级为首页模板
        private void InitTemplateType(int selectID)
        {
            //加载产品类型
            List<TemplateModel> dic_pro_types = db.Templates.GetList("TypeCode ='105003'");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });

            foreach (TemplateModel item in dic_pro_types)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Name, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Name });
                }
            }
            ViewData["selTemplate"] = selectTypes;
        }

        private void InitCategoryType(string selectID)
        {
            //加载产品类型
            List<CategoryModel> dic_pro_types = db.Categorys.GetList("");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "00", Text = "请选择" });

            foreach (CategoryModel item in dic_pro_types)
            {
                if (item.Code == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Code.ToString(), Text = item.Name, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Code.ToString(), Text = item.Name });
                }
            }
            ViewData["selCategory"] = selectTypes;
        }

         [ValidateInput(false)]
        public ActionResult Save(ArticleModel model)
        {
            string action = model.Action;

            //文章访问路径逻辑:域名/a/yyyyMMdd/ID.html
            //其中a 是保存所有文章的目录，此规则目前写死，以后可配置
            //创建时间
            model.CreateDate = DateTime.Now;
            model.Creator = CurrentUser.UserName;
            model.State = ArticleStateEnum.待发布.ToString();
            string result = SaveStateEnum.OK.ToString();
            try
            {
                if (action == ActionEnum.Create.ToString())
                {
                    if (!db.Articles.Exists(model.Title))
                    {
                        //随机产生一个文件名 格式：/a/201503/25/C1009R1324.html
                        Random rd = new Random(Guid.NewGuid().GetHashCode());
                        string urlTemp = @"/a/{0}/{1}N{2}.html";
                        model.Url = string.Format(urlTemp, DateTime.Now.ToString("yyyyMM/dd"),model.CategoryCode,rd.Next(1,100000));        

                        db.Articles.Add(model);
                    }
                    else
                    {
                        result = SaveStateEnum.NO.ToString();
                    }
                    
                }
                else if (action == ActionEnum.Update.ToString())
                {
                    db.Articles.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    db.Articles.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

    }
}
